<?php
namespace Home\Controller;
use Common\Controller\UserController;
class CartController extends UserController {
	public function addcart(){//加入购物车
        if(IS_AJAX){
            $cartModel=M('cart');
            $data=array(
                'comuser_id'=>session('id'),
                'merchandise_id'=>I('post.id'),
                'number'=>I('post.num'),
                'add_time'=>date('Y-m-d H:i:s',time()),
                );
            $result=$cartModel->where('merchandise_id='.I('post.id'))->find();
            if ($result) {
                $date['msg']='购物车已有该商品';
                $this->ajaxReturn($date);
            }else{
                if($cartModel->add($data)){
                    $date['status']='ok';
                    $date['msg']='添加购物车成功';
                    $this->ajaxReturn($date);
                }else{
                    $date['msg']='添加购物车失败';
                    $this->ajaxReturn($date);
                }
            }          
        }
    }
    public function cart(){//购物车页面
        if (session('id')) {
            $cart=$this->getcart();
            $this->assign('buycart',$cart);
        }else{
            header('Location:'.U('Index/login'));
        }    
        $this->display();
    }

    public function order_payment(){//确认订单页面
        $addressModel=M('address');
        $add=$addressModel->where('comuser_id='.session('id'))->select();
        $this->assign('tist',$add); 
        $carts=I('post.cart');
        foreach ($carts as $key => $cart) {
            $cartModel=M('cart');
            $date['number']=$cart['number'];
            $cartModel->where('id='.$cart['id'])->save($date);
        }
        $cart=$this->getcart();
        $this->assign('buycart',$cart);
        $this->display();
    }

    public function order(){
            if(I('post.address_id')){
                $address_id=I('post.address_id');
                $addressModel=M('address');
                $ress=$addressModel->where('id='.$address_id)->find();
                $this->assign('ress',$ress);
            } else {
                $this->error('请选择收货地址');
            } 
            $cart = $this->getcart();
            $total=0; 
            foreach ($cart as $key => $value) {
                 $total+=$value['number']*$value['price'];
             }  
            $this->assign('total',$total);
            $data=array(
            'comuser_id'=>session('id'),
            'address'=>$ress['name'] . ' '.$ress['address'].' '.$ress['phone'],
            'message'=>I('post.message'),
            'total'=>$total,
            'payment'=>I('post.radio1'),
            'fare_fa'=>I('post.radio'),
            'status'=>'1',
            'add_time'=>date('Y-m-d H:i:s',time()),
            );
            $orderModel=M('order');
            $order_id=$orderModel->add($data);
            $addModel=M('merchandise_order');
            foreach ($cart as $key => $val) {
                $date=array(
                'order_id'=>$order_id,
                'merchandise_id'=>$val['merchandise_id'],
                'merchandise'=>$val['merchandise'],
                'price'=>$val['price'],
                'number'=>$val['number'],
                'photos'=>$val['photos'],
                );
                $addModel->add($date);
            }

            $cartModel=M('cart');
            $count=$cartModel->where('comuser_id='.session('id'))->count();
            $this->assign('count',$count);

            $cartModel->where('comuser_id='.session('id'))->delete();

            $arr=$addModel->field('merchandise')->where('order_id='.$order_id)->find();
            $this->assign('name',$arr);

            $this->order_id=$order_id;
            $this->action=U('payNow');
            $this->display();
    }

    public function payNow(){
         $order_id = I('post.order',0,'intval');
        if($order_id>0){
            //准备支付数据
            $order = M('order')->find($order_id);
            //连接支付宝
            include THINK_PATH."Library/Org/Alipay/AopSdk.php";
            $alipay = new \AopClient;
            $alipay->gatewayUrl = "https://openapi.alipaydev.com/gateway.do";
            $alipay->appId = C('appId');
            $alipay->rsaPrivateKey = C('rsaPrivateKey');
            $alipay->format = C('format');
            $alipay->charset= C('charset');
            $alipay->signType= C('signType');
            $alipay->alipayrsaPublicKey = C('alipayrsaPublicKey');
            include THINK_PATH."Library/Org/Alipay/Aop/request/AlipayTradePagePayRequest.php";
            $request = new \AlipayTradePagePayRequest();
            $content="{" .
                "    \"out_trade_no\":\"".$order['id']."\"," .
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," .
                "    \"total_amount\":".$order['total']."," .
                "    \"subject\":\"新安网店\"," .
                "    \"body\":\"新安网店\"," .
                "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"," .
                "    \"extend_params\":{" .
                "    \"sys_service_provider_id\":\"2016080500169449\"" .
                "    }".
                "  }";
            $request->setBizContent($content);
            $request->setNotifyUrl(U('alipayNotify','',true,true));
            $request->setReturnUrl(U('alipayReturn','',true,true));
            $this->form = $alipay->pageExecute($request); //调用SDK生成表单
            $this->display();
        }else{
            $this->error("参数错误",'order_payment');
        }
    }


     public function alipayReturn(){
        //连接支付宝
        include THINK_PATH."Library/Org/Alipay/AopSdk.php";
        $aop = new \AopClient();
        $alipayrsaPublicKey = C('alipayPublicKey');
        $signtype = C('signType');
        $aop->alipayrsaPublicKey = $alipayrsaPublicKey;
        $arr=$_GET;
        $result = $aop->rsaCheckV1($arr, $alipayrsaPublicKey, $signtype);
        if($result){
            $order_id=$arr['out_trade_no'];
            if($order_id>0){
                $orderModel=M('Order');
                //开启事务
                $orderModel->startTrans();
                //查询订单
                
                $order=$orderModel->lock(true)->find($order_id);
                if($order&&$order['status']==1){
                    //查找商品准备扣除库存
                    $opModel=M('merchandise_order');
                    $pModel = M("merchandise");
                    $products = $opModel->where('order_id='.$order_id)->select();
                    foreach ($products as $key => $product) {
                        $re = $pModel->lock(true)->find($product['merchandise_id']);
                        // print_r($re);
                        // exit;
                        if($re&&$re['stock']>=$product['number']){
                            $pModel->stock=$re['stock']-$product['number'];
                            $status = $pModel->where("id={$product['merchandise_id']}")->save();
                            if(!$status){
                                $orderModel->rollback();
                                echo $re['merchandise'],"商品库存错误";
                                exit;
                            }
                        }else{
                            $orderModel->rollback();
                            echo $re['merchandise']," '商品库存不足'";
                            exit;
                        }
                    }
                    $orderModel->status=2;
                    $osStatus = $orderModel->where("id={$order_id}")->save();
                    if($osStatus){
                        $orderModel->commit();
                        header('Location:'.U('Order/order_list'));
                    }else{
                        $orderModel->rollback();
                        echo $re['merchandise'],"商品库存错误";
                        exit;
                    }
                }else{
                    echo "订单信息错误";
                }
            }
        }else{
            echo 'error';
        }
    }

    public function alipayNotify(){

    }

    public function delete(){
        $id=I('get.id',0,'intval');
        if ($id>0) {
           $cartModel=M('cart');
           $cartModel->where('id='.$id)->delete();
           echo "<script>alert('操作成功');location.href='".$_SERVER["HTTP_REFERER"]."';</script>";
        }
    }
}